﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace smp.RabbitMq.Strategies
{
    public class BasicSubscriberStrategy : ISubscriberStrategy
    {
        #region Implementation of ISubscriberStrategy

        public StrategyResult HandleMessage(List<ISubscriberHandler> handlers, Envelope envelope)
        {
            var success = true;

            var type = Type.GetType(envelope.MessageType);
            var message = JsonConvert.DeserializeObject(envelope.Message, type);
            if (message == null)
            {
                InstancesFactory.Log.Warning("Null or empty message entity recieved, or could not deserialize message {0} to type {1}", envelope.Message, envelope.MessageType);
                return new StrategyResult {Success = true};
            }

            foreach(var handler in handlers)
            {
                try
                {
                    ExecuteHandler(message, handler);
                }
                catch (Exception ex)
                {
                    InstancesFactory.Log.Error(ex);
                    success = false;
                }
            }
            return new StrategyResult {Success = success};
        }

        private void ExecuteHandler(object message, ISubscriberHandler handler)
        {
            var subscriberHandler = (dynamic)handler;
            var messageEntity = (dynamic) message;
            subscriberHandler.Handle(messageEntity);
        }

        #endregion
    }
}
